package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserLoginService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 使用HttpClient发送请求
        Map<String, String> parmasMap = new HashMap<>();
        parmasMap.put("appid", weChatProperties.getAppid());
        parmasMap.put("secret", weChatProperties.getSecret());
        parmasMap.put("js_code", userLoginDTO.getCode());
        parmasMap.put("grant_type", "authorization_code");
        String jsonRes = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", parmasMap);

        log.info("jsonRes: {}", jsonRes);

        // 解析jsonRes
        JSONObject res = JSON.parseObject(jsonRes);
        String openid = (String) res.get("openid");
        if(openid == null) {
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }

        // 3.判断是否为新用户，根据openid查询user表
        User user = userMapper.selectByOpenId(openid);

        if(user == null) {
            // 4.如果是新用户，初始化用户数据到user表中
            User insertUserInfo = User.builder()
                                        .openid(openid)
                                        .createTime(LocalDateTime.now())
                                        .name(openid.substring(0, 6))
                                        .build();
            userMapper.insert(insertUserInfo);

            return insertUserInfo;
        }

        // 5.否则，直接返回user对象数据
        return user;
    }
}
